﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

public partial class Reports_Grid : System.Web.UI.Page
{
	public string UserID
	{
		get { return this.Master.GetUserID(); }
	}

	public CustomControlsNS.CustomButton GetButton(string buttonID)
	{
		return this.Master.GetButton(buttonID);
	}

	protected void Page_Load(object sender, EventArgs e)
	{
		this.Page.Master.Page.Form.DefaultButton = btnView.UniqueID;

		CustomControlsNS.CustomButton cc = new CustomControlsNS.CustomButton(Resources.DatabaseStrings.btn_Refresh, Resources.DatabaseStrings.btn_Refresh, "$get('" + btnView.ClientID + "').click();", "1", true);
		cc.ID = "btn_Refresh";
		//this.Master.PageToolbarButtons.Add(cc);

		if (!IsPostBack)
		{
			Session["ds_ReportList"] = null;
			Session["ds_ReportDetails"] = null;
			Session["ds_ReportResult"] = null;
		}

		DataSet ds_ReportList = (DataSet)Session["ds_ReportList"];
		if (ds_ReportList == null)
		{
			ds_ReportList = Hipocrate.DB.DBConnection.GetData("GetReportDetails", new string[] { "UserID", "ID" }, new object[] { 1, Tools.GetSQLValue("") });
			Session["ds_ReportList"] = ds_ReportList;
		}
		if (ds_ReportList != null)
		{
			RepeaterGroups.DataSource = ds_ReportList.Tables[1].DefaultView;
			RepeaterGroups.DataBind();
		}

		if (Session["ds_ReportResult"] == null && TabContainer1.ActiveTabIndex > 1)
		{
			TabContainer1.ActiveTabIndex = 1;
			TabContainer1_ActiveTabChanged(null, null);
		}
		if (ViewState["RptID"] == null && TabContainer1.ActiveTabIndex > 0)
		{
			TabContainer1.ActiveTabIndex = 0;
			TabContainer1_ActiveTabChanged(null, null);
		}

		if (TabContainer1.ActiveTabIndex == 1)
		{
			DataSet ds_ReportDetails = (DataSet)Session["ds_ReportDetails"];
			if (ds_ReportDetails == null)
			{
				ds_ReportDetails = Hipocrate.DB.DBConnection.GetData("GetReportDetails", new string[] { "UserID", "ID" }, new object[] { 1, ViewState["RptID"] });
				Session["ds_ReportDetails"] = ds_ReportDetails;
			}
			if (ds_ReportDetails != null)
				LoadCriterias();
		}
		//GetButton("btn_Refresh").Enabled = (TabContainer1.ActiveTabIndex == 2);

		if (!IsPostBack)
		{
			if (!string.IsNullOrEmpty(Request.QueryString["RptID"]))
				DoSelectReport(Request.QueryString["RptID"]);

			if (!string.IsNullOrEmpty(Request.QueryString["RptID2"]))
			{
				DoSelectReport(Request.QueryString["RptID2"]);
				Hashtable ht = new Hashtable();

				for (int i = 0; i < Request.QueryString.Count; ++i)
					if (Request.QueryString.AllKeys[i] != "RptID" && Request.QueryString.AllKeys[i] != "RptID2")
						ht[Request.QueryString.AllKeys[i]] = new string[] { Request.QueryString[i], Request.QueryString[i] };

				ViewState["ht_CriteriasValues"] = ht;
				DoView(ht);
			}
		}
	}

	protected void Page_PreRender(object sender, EventArgs e)
	{
		if (!IsPostBack)
			TabContainer1_ActiveTabChanged(null, null);
	}

	protected DataView GetDataSource(string strModuleID)
	{
		DataView dv = new DataView(((DataSet)Session["ds_ReportList"]).Tables[0]);
		dv.RowFilter = "(ModuleID=" + strModuleID + ")";
		return dv;
	}

	protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
	{
		txtLastTab.Text = TabContainer1.ActiveTabIndex.ToString();
		switch (TabContainer1.ActiveTabIndex)
		{
			case 0:
				this.Page.Title = "Hipocrate - " + Resources.GridView.ReportsList;
				break;
			case 1:
				this.Page.Title = "Hipocrate - " + Resources.GridView.ReportCriterias + (lblRptName.Text != "" ? " - " + lblRptName.Text : "");
				break;
			case 2:
				this.Page.Title = "Hipocrate - " + Resources.GridView.ReportDisplay + (lblRptName.Text != "" ? " - " + lblRptName.Text : "");
				break;
			default:
				this.Page.Title = "Hipocrate - " + Resources.GridView.ReportsList;
				break;
		}
		//GetButton("btn_Refresh").Enabled = (TabContainer1.ActiveTabIndex == 2);
	}

	protected void lbSelectReport_Click(object sender, EventArgs e)
	{
		DoSelectReport(((LinkButton)sender).CommandArgument);
	}

	private void DoSelectReport(string strRptID)
	{
		ViewState["RptID"] = strRptID;
		TabContainer1.ActiveTabIndex = 1;

		DataSet ds_ReportDetails = Hipocrate.DB.DBConnection.GetData("GetReportDetails", new string[] { "UserID", "ID" }, new object[] { 1, ViewState["RptID"] });
		Session["ds_ReportDetails"] = ds_ReportDetails;
		Session["ds_ReportResult"] = null;
		ViewState["ht_CriteriasValues"] = null;

		lblRptName.Text = ds_ReportDetails.Tables[0].DefaultView[0]["Name_" + Tools.GetLanguage(Request)].ToString();
		lblDescription.Text = ds_ReportDetails.Tables[0].DefaultView[0]["Description_" + Tools.GetLanguage(Request)].ToString();

		TabContainer1_ActiveTabChanged(null, null);

		if (ds_ReportDetails != null)
			LoadCriterias();
	}

	protected void btnView_Click(object sender, EventArgs e)
	{
		if (TabContainer1.ActiveTabIndex != 1 && TabContainer1.ActiveTabIndex != 2)
			return;

		Hashtable ht = Tools.GetControlValues(tblCriterias);
		if (ViewState["ht_CriteriasValues"] == null || ht.Count > 0)
			ViewState["ht_CriteriasValues"] = ht;
		else
			if (ViewState["ht_CriteriasValues"] != null)
				ht = (Hashtable)ViewState["ht_CriteriasValues"];

		DoView(ht);
	}

	protected void DoView(Hashtable ht)
	{
		TabContainer1.ActiveTabIndex = 2;
		TabContainer1_ActiveTabChanged(null, null);

		string strCriterias = "";
		foreach (string strKey in ht.Keys)
			if (((string[])ht[strKey])[0] != "")
				strCriterias += Tools.GetHeaderText(strKey) + " = '" + ((string[])ht[strKey])[1] + "', ";
		strCriterias = (strCriterias.Length > 0) ? strCriterias.Substring(0, strCriterias.Length - 2) : strCriterias;
		strCriterias = (strCriterias.Length > 0) ? "( " + strCriterias + " )" : strCriterias;
		lblCriterias.Text = strCriterias;

		DataSet ds = (DataSet)Session["ds_ReportDetails"];
		DataView dv0 = ds.Tables[0].DefaultView;
		DataView dv2 = ds.Tables[2].DefaultView;
		DataView dv4 = ds.Tables[4].DefaultView;
		string strRptID = dv0[0]["ID"].ToString();
		string strRptName = dv0[0]["Name_" + Tools.GetLanguage(Request)].ToString();
		string strProcedureName = dv0[0]["ProcedureName"].ToString();
		string strDatabaseName = dv0[0]["DatabaseName"].ToString();
		dv4.RowFilter = "[PARAMETER_NAME] <> '@RETURN_VALUE' AND [PARAMETER_NAME] <> '@TABLE_RETURN_VALUE'";

		string[] arParamNames = new string[dv4.Count];
		object[] arParamValues = new object[dv4.Count];
		ArrayList arParamNamesAndValues = new ArrayList();
		for (int i = 0; i < dv4.Count; ++i)
		{
			arParamNames[i] = dv4[i]["PARAMETER_NAME"].ToString().Substring(1);
			arParamValues[i] = Tools.GetSQLValue((ht != null && ht[arParamNames[i]] != null ? ((string[])ht[arParamNames[i]])[0] : ""), dv4[i]["TYPE_NAME"].ToString(), Tools.GetLanguage(Request));
			if (arParamNames[i] == "UserID" && arParamValues[i] == System.DBNull.Value)
				arParamValues[i] = this.UserID;
			if (arParamValues[i] != System.DBNull.Value)
				arParamNamesAndValues.Add("@" + arParamNames[i] + "=" + arParamValues[i].ToString());
		}
		string[] arParamNamesAndValues2 = new string[arParamNamesAndValues.Count];
		arParamNamesAndValues.CopyTo(arParamNamesAndValues2);

		int nResult = 0;
		DateTime dt1 = DateTime.Now;
		DateTime dt2 = DateTime.Now;
		DataSet ds1 = null;
		try
		{
			dt1 = DateTime.Now;
			ds1 = Hipocrate.DB.DBConnection.GetData(strProcedureName, arParamNames, arParamValues, strDatabaseName, GetProcedureType(strProcedureName, strDatabaseName));
			dt2 = DateTime.Now;
			Session["ds_ReportResult"] = ds1;

			GridViewReportDetails.SessionKey = "ds_ReportResult";
			GridViewReportDetails.SessionKeyIndex = 0;
            if (ds1.Tables.Count > 0)
            {
                GridViewReportDetails.SessionKeyFilter = ds1.Tables[0].DefaultView.RowFilter;
            }
			GridViewReportDetails.CaptionForXLS = strRptName;
			GridViewReportDetails.SessionKeyColumnHeadersIndex = 1;
			if (dv0[0]["PageSize"] != System.DBNull.Value && dv0[0]["PageSize"].ToString() != "")
			{
				GridViewReportDetails.AllowPaging = true;
				GridViewReportDetails.PageSize = Convert.ToInt32(dv0[0]["PageSize"]);
			}
			else
			{
				GridViewReportDetails.AllowPaging = false;
				GridViewReportDetails.PageSize = -1;
			}

			GridViewReportDetails.HiddenColumns = dv0[0]["HiddenColumns"].ToString().Split(new char[] { ',' });
			GridViewReportDetails.TotalColumns = dv0[0]["TotalColumns"].ToString();
			GridViewReportDetails.TotalOnAllDecimalColumns = Convert.ToBoolean(dv0[0]["TotalOnAllDecimalColumns"]);

            if (dv2.Count > 0)
            {
                GridViewReportDetails.LinkColumn = Tools.GetArrayFromColumn(dv2, "LinkColumn");
                GridViewReportDetails.LinkFormat = Tools.GetArrayFromColumn(dv2, "LinkFormat");
                //GridViewReportDetails.LinkFields = Tools.GetArrayFromColumn(dv2, "LinkFields");
                GridViewReportDetails.LinkInNewWindow = Tools.GetArrayFromColumn(dv2, "LinkInNewWindow");
            }

            if (ds1.Tables.Count > 0)
            {
                GridViewReportDetails.DataSource = ds1.Tables[0].DefaultView;
                GridViewReportDetails.DataBind();
            }
            else
            {
                GridViewReportDetails.SessionKey = "";
                GridViewReportDetails.SessionKeyIndex = 0;
                GridViewReportDetails.SessionKeyFilter = "";

                GridViewReportDetails.DataSource = new DataView();
                GridViewReportDetails.DataBind();
            }
		}
		catch (Exception ex)
		{
			nResult = -1;
			this.Master.SetMessage(ex.Message, true);

			GridViewReportDetails.SessionKey = "";
			GridViewReportDetails.SessionKeyIndex = 0;
			GridViewReportDetails.SessionKeyFilter = "";

			GridViewReportDetails.DataSource = new DataView();
			GridViewReportDetails.DataBind();
		}
		finally
		{
			lblReportTime.Text = " (" + Resources.GridView.ReportGenerateTime + " = " + dt2.Subtract(dt1).TotalSeconds.ToString("N4") + " sec)";
			if (nResult >= 0)
				foreach (DataTable dt in ds1.Tables)
					nResult += dt.Rows.Count;
			Hipocrate.DB.DBConnection.Execute("InsertLOG", new string[] { "UserID", "RptID", "RptParams", "ExecutionTime", "Result" }, new object[] { this.UserID, strRptID, Tools.GetSQLValue(string.Join(",", arParamNamesAndValues2)), Convert.ToDecimal(dt2.Subtract(dt1).TotalSeconds), nResult });
		}

		lblRptID.Text = "RptID=" + strRptID;
		lblRptName2.Text = ds.Tables[0].DefaultView[0]["Name_" + Tools.GetLanguage(Request)].ToString();
		lblDescription2.Text = ds.Tables[0].DefaultView[0]["Description_" + Tools.GetLanguage(Request)].ToString();

		lblExplanations.Text = "\n<BR />" + string.Format(Resources.GridView.EXPL_LinesPerPage, Resources.GridView.LinesPerPage);
		lblExplanations.Text += "\n<BR />" + string.Format(Resources.GridView.EXPL_Filter, Resources.GridView.NoFilter);
		lblExplanations.Text += "\n<BR />" + Resources.GridView.EXPL_Excel;
		DataView dv = new DataView(((DataSet)Session["ds_ReportList"]).Tables[0]);
		foreach (DataRowView drv2 in dv2)
		{
			dv.RowFilter = "ID = " + drv2["TargetRptID"].ToString();
			if (dv.Count > 0)
				lblExplanations.Text += "\n<BR />" + string.Format(Resources.GridView.EXPL_Link, Tools.GetHeaderText(drv2["LinkColumn"].ToString()), dv[0]["Name_" + Tools.GetLanguage(Request)].ToString());
		}
		lblExplanations.Text += "\n";
	}

	protected void OnClick_btnReset(object sender, EventArgs e)
	{
		Tools.SetControlDefaultValues(tblCriterias);
	}

	private void LoadCriterias()
	{
		if (ViewState["RptID"] == null)
		{
			TabContainer1.ActiveTabIndex = 0;
			TabContainer1_ActiveTabChanged(null, null);
			return;
		}

		if (Session["ds_ReportDetails"] == null)
			Response.Redirect("Reports.aspx");

		Hashtable ht = (Hashtable)ViewState["ht_CriteriasValues"];

		DataSet ds = (DataSet)Session["ds_ReportDetails"];
		DataView dv0 = ds.Tables[0].DefaultView;
		DataView dv3 = ds.Tables[3].DefaultView;
		DataView dv4 = ds.Tables[4].DefaultView;
		if (dv0.Count == 0)
			return;

		string strAdvancedCriterias = dv0[0]["AdvancedCriterias"].ToString();
		string[] arAdvancedCriterias = strAdvancedCriterias.Split(new char[] { ',' });
		dv4.RowFilter = "[PARAMETER_NAME] <> '@RETURN_VALUE' AND [PARAMETER_NAME] <> '@TABLE_RETURN_VALUE' AND [PARAMETER_NAME] <> '@UserID'";

		TableRow tr = null;
		TableCell td = null;
		Control c = null;
		bool bFirst = true;
		foreach (DataRowView drv4 in dv4)
		{
			string strParameterName = drv4["PARAMETER_NAME"].ToString().Substring(1);
			string strParameterType = drv4["TYPE_NAME"].ToString();

			tr = new TableRow();
			tr.CssClass = "clsTableReportTr";
			tblCriterias.Rows.AddAt(tblCriterias.Rows.Count - 1, tr);

			td = new TableCell();
			tr.Cells.Add(td);
			td.CssClass = "RptCriteriaHeader";
			td.Wrap = false;
			td.Text = Tools.GetHeaderText(strParameterName);

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;

			dv3.RowFilter = "[Column] = '" + strParameterName + "'";
			if (strParameterType == "bit")
			{
				c = new DropDownList();
				c.ID = "ddl" + strParameterName;
				((DropDownList)c).Width = Unit.Pixel(300);
				((DropDownList)c).Items.Add(new ListItem("", ""));
				((DropDownList)c).Items.Add(new ListItem(Resources.GridView.No, "0"));
				((DropDownList)c).Items.Add(new ListItem(Resources.GridView.Yes, "1"));
				if (ht != null && ht[strParameterName] != null)
					((DropDownList)c).SelectedValue = ((string[])ht[strParameterName])[0];
			}
			else if (dv3.Count == 0)
			{
				c = new TextBox();
				c.ID = "txt" + strParameterName;
				((TextBox)c).Width = Unit.Pixel(300);
				if (ht != null && ht[strParameterName] != null)
					((TextBox)c).Text = ((string[])ht[strParameterName])[0];
			}
			else
			{
				c = new DropDownList();
				c.ID = "ddl" + strParameterName;
				((DropDownList)c).Width = Unit.Pixel(300);
				int nDdl = GetTableNo(ds, 3, strParameterName);
				if (nDdl >= 0)
					FillDropDownList((DropDownList)c, ds.Tables[6 + nDdl].DefaultView, Convert.ToBoolean(dv3[0]["Translated"]));
				if (ht != null && ht[strParameterName] != null)
					((DropDownList)c).SelectedValue = ((string[])ht[strParameterName])[0];
			}
			td.Controls.Add(c);

			td = new TableCell();
			tr.Cells.Add(td);
			td.CssClass = "Explicatii";
			td.Wrap = false;

			switch (strParameterType)
			{
				case "bit":
					td.Text = " (" + Resources.GridView.Type_Bit + ")";
					break;
				case "bigint":
				case "int":
				case "smallint":
				case "tinyint":
					td.Text = " (" + Resources.GridView.Type_Int + ")";
					break;
				case "decimal":
				case "numeric":
				case "float":
				case "real":
				case "money":
				case "smallmoney":
					td.Text = " (" + Resources.GridView.Type_Decimal + ")";
					break;
				case "datetime":
				case "smalldatetime":
					td.Text = " (" + Resources.GridView.Type_Date + " " + Tools.GetDateFormat() + ")";

					CalendarExtender ce = new CalendarExtender();
					ce.TargetControlID = c.ID;
					ce.CssClass = "MyCalendar";
					ce.Format = Tools.GetDateFormat();
					c.Parent.Controls.Add(ce);
					break;
				case "varchar":
				case "char":
				case "text":
				case "nvarchar":
				case "nchar":
				case "ntext":
					td.Text = " (" + Resources.GridView.Type_Text + ")";
					break;
				default:
					td.Text = " (" + strParameterType + ")";
					break;
			}
			if (c is DropDownList)
				td.Text = " (" + Resources.GridView.Type_List + ")";

			int x = Tools.ArrayIndexOf(arAdvancedCriterias, strParameterName);
			if (x != -1)
			{
				arAdvancedCriterias[x] = c.ClientID;
				tr.Style.Add("display", "none");
			}

			if (bFirst)
			{
				this.Page.Master.Page.Form.DefaultFocus = c.ClientID;
				bFirst = false;
			}
		}
	}

	private void FillDropDownList(DropDownList d, DataView dv, bool bTranslated)
	{
		d.Items.Clear();
		foreach (DataRowView drv in dv)
		{
			ListItem li = new ListItem(bTranslated ? Tools.GetHeaderText(drv["Name"].ToString()) : drv["Name"].ToString(), drv["ID"].ToString());
			d.Items.Add(li);
		}
		d.Items.Insert(0, new ListItem("", ""));
	}

	private int GetTableNo(DataSet ds, int nParamsTable, string strParameterName)
	{
		DataView dv = new DataView(ds.Tables[nParamsTable], "Column = '" + strParameterName + "'", "", DataViewRowState.OriginalRows);
		if (dv.Count > 0)
			return dv.Table.Rows.IndexOf(dv[0].Row);
		else
			return -1;
	}

	private int GetProcedureType(string strProcedureName, string strDatabaseName)
	{
		int nProcedureType = 0;
		DataSet dsType = Hipocrate.DB.DBConnection.GetData("sp_help", new string[] { "objname" }, new object[] { Tools.GetSQLValue(strProcedureName) }, strDatabaseName, 1);
		switch (dsType.Tables[0].DefaultView[0]["Type"].ToString())
		{
			case "view":
			case "user table":
			case "internal table":
			case "system table":
				nProcedureType = 0;
				break;
			case "stored procedure":
			case "extended stored proc":
				nProcedureType = 1;
				break;
			case "inline function":
			case "scalar function":
			case "table function":
				nProcedureType = 2;
				break;
		}
		return nProcedureType;
	}

}
